package cn.lagou.Homework.MergeData

import scala.collection.mutable.ArrayBuffer

object MergeData {
  val Data: Array[(String, String, Int, Int)] =
    Array( ("UserA","LocationA",8,60),
      ("UserA","LocationA",9,60),
      ("UserB","LocationB",10,60),
      ("UserB","LocationB",11,80),
      ("UserB","LocationB",13,80)
    )

  def main(args: Array[String]): Unit = {
    val sortedData = Data.sortBy(x => x._1 + x._2 + f"${x._3}%02d") //
    merge(sortedData).foreach(println)
  }

  private def merge(sortedData: Array[(String, String, Int, Int)]):Array[(String, String, Int, Int)] = {
    var (merged_username:String, merged_location:String, merged_init:Int, merged_period:Int)  = ("", "", 0, 0)
    var result:ArrayBuffer[(String, String, Int, Int)] = ArrayBuffer[(String, String, Int, Int)]() //暂存数据
    for (item <- sortedData) {
      // id不等或者时间连接不上 直接添加暂存数据
      val (username,location,init, period) = item
      if ((merged_username, merged_location) != (username, location) || (merged_init * 60 + merged_period) < (init * 60))
      {
        result += ((merged_username, merged_location, merged_init, merged_period))
        merged_username = username;merged_location=location; merged_init=init;merged_period=period
      } else { // id 相等且连接的上，修改暂存的period值
        merged_period = math.max(merged_period, (init-merged_init)*60 + period)
      }
    }
    result += ((merged_username, merged_location, merged_init, merged_period))
    result.tail.toArray
  }
}
